#include "opengl_context_win32.h"
#include <gl/gl.h>

using namespace krryn::system;

opengl_context_win32::opengl_context_win32(HWND hWnd, opengl_context_win32 *a_Share){
	// NOTICE (or BIG FAT WARNING)
	// In order for wglShareLists to work all contexts need to be created
	// in the same thread.

	hDC = GetDC(hWnd);
	setup_pixel_format();
	hRC = wglCreateContext(hDC);
	this->hWnd = hWnd;

	if(a_Share){
		wglShareLists(a_Share->hRC, hRC);
	}
}

opengl_context_win32::~opengl_context_win32(){
	ReleaseDC(hWnd, hDC);

	if(wglGetCurrentContext()){
 		wglDeleteContext(hRC);
	}
}

void opengl_context_win32::attach(){
	wglMakeCurrent(hDC, hRC);
}

void opengl_context_win32::detach(){
	wglMakeCurrent(hDC, NULL);
}

void opengl_context_win32::swap_buffers(){
	SwapBuffers(hDC);
}

void opengl_context_win32::setup_pixel_format(){
	static PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),	// size of this pfd
		1,				// version number
		PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL,
		PFD_TYPE_RGBA,			// RGBA type
		32,				// 24-bit color depth
		0, 0, 0, 0, 0, 0,
		0, 0, 0, 0, 0, 0, 0, 			// accum bits ignored
		32,				// 32-bit z-buffer	
		0,				// no stencil buffer
		0,				// no auxiliary buffer
		PFD_MAIN_PLANE,			// main layer
		0, 0, 0, 0				// layer masks ignored
	};

	int pf;
	pf = ChoosePixelFormat(hDC, &pfd);
	SetPixelFormat(hDC, pf, &pfd);
}